<!-- components/ImageEditor.vue -->
<template>
  <view class="editor-container">
    <!-- 修改后的贴纸容器 -->
    <view class="edit-area" @touchmove.prevent>
    <image 
           :src="baseImage" 
           mode="aspectFit" 
           class="base-image"
           v-if="baseImage"
           @load="handleImageLoad"
         />
       <!-- 贴纸元素 -->
          <view 
            v-for="(sticker, index) in stickers"
            :key="index"
            class="sticker-item"
            :style="{
              left: sticker.x + 'px',
              top: sticker.y + 'px',
              transform: `scale(${sticker.scale}) rotate(${sticker.rotate}deg)`,
              zIndex: sticker.zIndex
            }"
            @touchstart="handleTouchStart(index, $event)"
            @touchmove="handleTouchMove(index, $event)"
            @touchend="handleTouchEnd"
          >
     <!-- 删除按钮 -->
           <view class="delete-btn" @tap.stop="removeSticker(index)">×</view>
           
           <!-- 缩放旋转控制点 -->
           <view 
             class="scale-handle"
             @touchstart.stop="handleScaleStart(index, $event)"
             @touchmove.stop="handleScaleMove(index, $event)"
             @touchend.stop="handleScaleEnd"
           ></view>
           
           <!-- 贴纸内容 -->
           <view class="sticker-content">
             <image 
               :src="sticker.url" 
               mode="widthFix"
               class="sticker-image"
             />
           </view>
      </view>
    </view>

    <scroll-view class="sticker-picker" scroll-x>
      <view 
        v-for="(sticker, index) in availableStickers"
        :key="'picker'+index"
        class="sticker-option"
        @click="addSticker(sticker)"
      >
        <image :src="sticker.thumbnail" mode="aspectFill" />
      </view>
    </scroll-view>

    <view class="action-buttons">
      <button @click="handleReset">重置</button>
      <button @click="handleConfirm">确认合成</button>
    </view>

    <fake-progress 
      :visible="showProgress"
      :isDone="syntheticDone"
      @cancel="handleProgressCancel"
    />
  </view>
</template>

<script>
import FakeProgress from './FakeProgress.vue'

export default {
  components: { FakeProgress },
  props: {
    baseImage: String,
    availableStickers: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      stickers: [],
      activeIndex: -1,
      startX: 0,
      startY: 0,
      showProgress: false,
      syntheticDone: false,
      velocityX: 0,
      velocityY: 0,
      lastMoveTime: 0,
      scaleStart: { x: 0, y: 0, distance: 0 },
      containerSize: { width: 0, height: 0 },
	  
      // 拖动相关数据
      dragData: {
        activeIndex: -1,
        startX: 0,
        startY: 0,
        offsetX: 0,
        offsetY: 0
      },
      // 缩放相关数据
      scaleData: {
        activeIndex: -1,
        startDistance: 0,
        startAngle: 0,
        initialScale: 1,
        initialRotate: 0
      },
    }
  },
  methods: {
    // 修改图片加载处理方法
    async handleImageLoad(e) {
      // 获取图片实际渲染尺寸
      const query = uni.createSelectorQuery().in(this)
      query.select('.base-image').boundingClientRect(res => {
        this.containerSize = {
          width: res.width,
          height: res.height
        }
      }).exec()
      
      // 获取图片原始尺寸备用
      this.imageOriginalSize = {
        width: e.detail.width,
        height: e.detail.height
      }
    },
 // 修改添加贴纸方法
    addSticker(sticker) {
      if(this.stickers.some(s => s.type === sticker.type)) return
      
      // 计算居中位置（基于实际显示尺寸）
      const centerX = this.containerSize.width / 2 - 50
      const centerY = this.containerSize.height / 2 - 50
      
      this.stickers.push({
        ...sticker,
        x: Math.max(0, Math.min(centerX, this.containerSize.width - 100)),
        y: Math.max(0, Math.min(centerY, this.containerSize.height - 100)),
        scale: 1,
        zIndex: this.stickers.length + 1
      })
    },
    removeSticker(index) {
      this.stickers.splice(index, 1)
    },
    // ========== 拖动处理 ==========
    handleTouchStart(index, e) {
			   console.log(e)
      const touch = e.touches[0]
      this.dragData = {
        activeIndex: index,
        startX: touch.clientX,
        startY: touch.clientY,
        offsetX: touch.clientX - this.stickers[index].x,
        offsetY: touch.clientY - this.stickers[index].y
      }
    },
	// 修改边界检查逻辑
     handleTouchMove(index, e) {
       if (this.dragData.activeIndex !== index) return
       if (this.scaleData.activeIndex !== -1) return // 缩放时禁用拖动
 
       const touch = e.touches[0]
       const newX = touch.clientX - this.dragData.offsetX
       const newY = touch.clientY - this.dragData.offsetY
 
       // 边界限制
       const stickerSize = 100 * this.stickers[index].scale
       this.stickers[index].x = Math.max(0, 
         Math.min(newX, this.containerSize.width - stickerSize))
       this.stickers[index].y = Math.max(0, 
         Math.min(newY, this.containerSize.height - stickerSize))
     },
	 
	     handleTouchEnd() {
	       this.dragData.activeIndex = -1
	     },
   handleScaleStart(index, e) {
	   console.log(e)
      const touch1 = e.touches[0]
      const touch2 = e.touches[1] || touch1
      
      const dx = touch2.clientX - touch1.clientX
      const dy = touch2.clientY - touch1.clientY
      this.scaleData = {
        activeIndex: index,
        startDistance: Math.hypot(dx, dy),
        startAngle: Math.atan2(dy, dx) * 180 / Math.PI,
        initialScale: this.stickers[index].scale,
        initialRotate: this.stickers[index].rotate
      }
    },
    handleScaleMove(index, e) {
      if (this.scaleData.activeIndex !== index) return

      const touch1 = e.touches[0]
      const touch2 = e.touches[1] || touch1
      const dx = touch2.clientX - touch1.clientX
      const dy = touch2.clientY - touch1.clientY
      
      // 计算缩放
      const currentDistance = Math.hypot(dx, dy)
      const scale = this.scaleData.initialScale * 
                   (currentDistance / this.scaleData.startDistance)
      
      // 计算旋转
      const currentAngle = Math.atan2(dy, dx) * 180 / Math.PI
      const rotate = this.scaleData.initialRotate + 
                    (currentAngle - this.scaleData.startAngle)

      // 更新数据
      this.stickers[index].scale = Math.min(Math.max(0.5, scale), 3)
      this.stickers[index].rotate = rotate % 360

      // 同步更新位置防止溢出
      const stickerSize = 100 * this.stickers[index].scale
      this.stickers[index].x = Math.max(0, 
        Math.min(this.stickers[index].x, 
        this.containerSize.width - stickerSize))
      this.stickers[index].y = Math.max(0, 
        Math.min(this.stickers[index].y, 
        this.containerSize.height - stickerSize))
    },

    handleScaleEnd() {
      this.scaleData.activeIndex = -1
    },
    clearSpeed() {
      this.velocityX = 0
      this.velocityY = 0
    },
    async handleConfirm() {
      this.showProgress = true
      this.syntheticDone = false
      
      // 使用canvas合成图片
      const canvas = uni.createCanvasContext('syntheticCanvas')
      await this.drawBaseImage(canvas)
      await this.drawStickers(canvas)
      
      // 生成图片
      const tempFilePath = await this.generateImage(canvas)
      
      // 模拟合成完成
      setTimeout(() => {
        this.syntheticDone = true
        this.$emit('synthetic', tempFilePath)
      }, 1500)
    },
    async drawBaseImage(canvas) {
      return new Promise((resolve) => {
        canvas.drawImage(this.baseImage, 0, 0, 
          this.containerSize.width, this.containerSize.height)
        resolve()
      })
    },
    async drawStickers(canvas) {
      this.stickers.forEach(sticker => {
        canvas.save()
        canvas.translate(sticker.x, sticker.y)
        canvas.scale(sticker.scale, sticker.scale)
        canvas.drawImage(sticker.url, 0, 0, 100, 100)
        canvas.restore()
      })
    },
    generateImage(canvas) {
      return new Promise((resolve) => {
        canvas.draw(false, () => {
          uni.canvasToTempFilePath({
            canvasId: 'syntheticCanvas',
            success: res => resolve(res.tempFilePath)
          })
        })
      })
    },
    handleReset() {
      this.stickers = []
    },
    handleProgressCancel() {
      this.showProgress = false
      this.syntheticDone = false
    }
  }
}
</script>


<style>
.editor-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #fff;
}



.base-image {
  width: 100%;
  height: 100%;
}



.sticker-image {
  width: 100%;
  height: 100%;
    pointer-events: none;
}

.sticker-controls {
  position: absolute;
  top: -10px;
  right: -10px;
  pointer-events: none;
}





.sticker-picker {
  height: 100px;
  white-space: nowrap;
  background: #fff;
  border-top: 1px solid #ddd;
  padding: 10px 0;
}

.sticker-option {
  display: inline-block;
  width: 80px;
  height: 80px;
  margin: 0 10px;
  border: 1px solid #ddd;
  border-radius: 8px;
  overflow: hidden;
}

.sticker-option image {
  width: 100%;
  height: 100%;
}

.action-buttons {
  padding: 10px;
  background: #fff;
  display: flex;
  gap: 10px;
  border-top: 1px solid #ddd;
}

.action-buttons button {
  flex: 1;
  background: #07c160;
  color: white;
  border-radius: 20px;
}
/* 添加容器尺寸限制 */
/* 修改后的样式 */
.edit-area {
  position: relative;
  width: 100vw;
  height: 70vh;
  overflow: hidden; /* 超出部分隐藏 */
}
.base-image {
  width: 100%;
  height: 100%;
  object-fit: contain; /* 确保图片适配容器 */
}

/* 优化控制点交互 */
.sticker-item {
  position: absolute;
  width: 100px;
  height: 100px;
  transform-origin: center center;
  touch-action: none;
}

.scale-handle {
  position: absolute;
  bottom: -12px;
  right: -12px;
  width: 24px;
  height: 24px;
  background: #07c160;
  border-radius: 50%;
  z-index: 2;
  touch-action: none;
}

.delete-btn {
  position: absolute;
  top: -12px;
  left: -12px;
  width: 24px;
  height: 24px;
  background: #ff4444;
  border-radius: 50%;
  color: white;
  text-align: center;
  line-height: 24px;
  font-size: 18px;
  z-index: 2;
  touch-action: none;
}

.sticker-content {
  width: 100%;
  height: 100%;
  overflow: hidden;
}
</style>